package secret.hehe.com.secret.Util;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import secret.hehe.com.secret.Activity.MainActivity;
import secret.hehe.com.secret.R;

import static secret.hehe.com.secret.Util.Util.doInsert;
import static secret.hehe.com.secret.Util.Util.doUpdate;

/**
 * Created by DELL on 2018/3/1.
 */

public class MessageService  extends Service {

    private String recvid;
    private int isConnection=0;
    private Context context;
    //获取消息线程
    private MessageThread messageThread = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(final Intent intent, int flags, int startID) {

        try {
            setRecvid(intent.getStringExtra("recvid"));
            context = this;
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(getRecvid());
        //开启线程
        messageThread = new MessageThread();
        messageThread.isRunning = true;
        messageThread.start();


        return super.onStartCommand(intent, flags, startID);
    }

    @Override
    public void onDestroy() {
        //System.exit(0);
        try {
            messageThread.isRunning=false;
        }catch (Exception e){
            e.printStackTrace();
        }
        super.onDestroy();
    }

    public void setRecvid(String recvid){
        this.recvid = recvid;
    }
    public String getRecvid(){
        return this.recvid;
    }

    class MessageThread extends Thread {
        //运行状态，下一步骤有大用
        public boolean isRunning = true;

        public void run() {
            while (isRunning) {
                try {
                    //休息30s
                    Thread.sleep(30000);
                    //获取服务器消息
                    String urlString = getApplicationContext().getResources().getString(R.string.serverURL);
                    urlString+="/email/getNewEmail";
                    URL url = new URL(urlString);
                    // url.openConnection()打开网络链接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setUseCaches(false);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Accept-Charset", "utf-8");
                    connection.setRequestProperty("Connection", "keep-alive");
                    String params = "recvid=" + getRecvid();
                    connection.getOutputStream().write(params.getBytes());
                    String jsonString="";
                    if (connection.getResponseCode() == 200) {
                        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        jsonString = "";
                        String readline = null;
                        while ((readline = bufferedReader.readLine()) != null) {
                            jsonString += readline;
                        }
                        inputStreamReader.close();

                        JSONObject jsonObject = new JSONObject(jsonString);
                        int code = jsonObject.getInt("code");
                        if(code == 200){
                            //有新消息
                            JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));
                            for(int i=0;i<jsonArray.length();i++)
                            {//存入数据库
                                JSONObject json = (JSONObject)jsonArray.opt(i);
                                json.put("issend",1);
                                JSONArray messageData = new JSONArray();
                                messageData.put(json);
                                doInsert("message",messageData,getApplicationContext());
                            }
                            //发通知
                            Notification notification = new NotificationCompat.Builder(getApplicationContext())
                                    .setWhen(System.currentTimeMillis()).setAutoCancel(true).setContentTitle("新消息")
                                    .setDefaults(Notification.DEFAULT_ALL).setContentText("你有未读消息")
                                    .setSmallIcon(R.mipmap.ic_launcher).build();
                            NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
                            notificationManager.notify(0, notification);


                            isConnection=0;

                            //发送至activity
                            LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
                            Intent intent = new Intent("new_message");
                            intent.putExtra("new_message",0);
                            localBroadcastManager.sendBroadcast(intent);
                        }else{
                            System.out.println("无消息");
                        }
                    } else {
                        isConnection++;
                        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
                        Intent intent = new Intent("new_message");
                        intent.putExtra("new_message",isConnection);
                        localBroadcastManager.sendBroadcast(intent);
                        System.out.println("链接失败");
                    }

                } catch (Exception e) {
                    isConnection++;
                    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
                    Intent intent = new Intent("new_message");
                    intent.putExtra("new_message",isConnection);
                    localBroadcastManager.sendBroadcast(intent);
                    e.printStackTrace();
                }
            }
        }
    }

}
